<template>
  <div class="queue-wrap">
    <continer :showPage="showPage" :isNoTabs="true">
      <template slot="search">
        <QuickSearch :advForm="quickSearchForm" @QuickSearch="queryList"></QuickSearch>
      </template>
      <template slot="oprate">
        <el-button type="primary" size="mini" @click="queryList">查询</el-button>
        <el-button size="mini" @click="addBtnFun" v-functions="['workorder_setting_satisfaction_insert']">新增</el-button>
      </template>
      <template slot="content">
        <instiutionTable ref="tableRef"
                         class="instiutionTable"
                         :pages="queueTablePages"
                         :instiutionTableData="queueTableData"
                         :instiutionTableHeader="queueTableHeader"
                         :batchOperate="batchOperate"
                         @batchClick="batchClick"
                         @sizeChange="sizeChange"
                         @currentChange="currentChangeFun">
                         <template #oper='{scope}'>
                           <span class="opera-span" @click.stop="handleEdit(scope.row)" v-functions="['workorder_setting_satisfaction_edit']">编辑</span>
                           <span class="opera-span danger" @click.stop="switchStatus(scope.row, 0)" v-if="scope.row.status === 1" v-functions="['workorder_setting_satisfaction_enable']">停用</span>
                           <span class="opera-span" @click.stop="switchStatus(scope.row, 1)" v-if="scope.row.status === 0" v-functions="['workorder_setting_satisfaction_enable']">启用</span>
                           <span class="opera-span danger" @click.stop="handleDel(scope.row)" v-functions="['workorder_setting_satisfaction_delete']">删除</span>
                         </template>
        </instiutionTable>
      </template>
      <template slot="page">
        <addOrEditSatisf :agentList="agentListArr" :titleArr="titleArr" @saveFun="saveFun" @cancelFun="back" ref="addOrEditSatisfRef" @pageBack="pageBack"></addOrEditSatisf>
      </template>
    </continer>
  </div>
</template>

<script lang="ts">
import { Component, Vue, Ref } from 'vue-property-decorator'
import { deepClone, commonAction } from '@/utils/common'
import { checkPermission } from '@/utils/directive'
import { CommonModule } from '@/store/modules/common'
import QuickSearch from '@/common/views/advancedSearch/QuickSearch.vue'
import instiutionTable from '@/common/views/institutionTable/institutionTable.vue'
import continer from '@/common/views/configCommon/ui-modules/handle-wrapper.vue'
import breadcrumb from '@/components/breadcrumb/breadcrumb.vue'
import addOrEditSatisf from './addOrEditSatisf.vue'
import { organizationConfigModule } from '@/store/modules/config/organizationConfig/index'
@Component({
  name: 'queue',
  components: {
    QuickSearch,
    instiutionTable,
    breadcrumb,
    addOrEditSatisf,
    continer
  }
})
export default class Queue extends Vue {
  [x: string]: any
  private showPage: boolean = false
  @Ref() private readonly addOrEditSatisfRef !: addOrEditSatisf
  @Ref() private readonly tableRef !: instiutionTable
  private quickSearchForm = {
    form: {
      name: ''
    },
    advSearchOptions: [ // 高级搜索数据
      { label: '满意度名称', inputType: 'input', placeholder: '请输入满意度名称', name: 'name' }
    ]
  }

  private batchOperate = [ // 批量操作设置
    { name: '批量删除', action: 'batchDelAgentFun', _id: 'skillGroup_management_batch_delete' }
  ]

  private titleArr: any[] = []

  private queueTablePages = { // 表格分页
    current: 1,
    pageSize: 10,
    total: 0
  }

  private queueTableData = []

  public statusMap = Object.freeze({
    1: { name: '启用', iconClass: 'green-color V7_iconV7tubiao_dian' },
    0: { name: '停用', iconClass: 'red-color V7_iconV7tubiao_dian' }
  })

  private queueTableHeader: any[] = [ // 表头
    { label: '满意度名称', prop: 'name' },
    { label: '创建时间', prop: 'createTime' },
    { label: '最后更新时间', prop: 'updateTime' },
    { label: '更新人', prop: 'updateUser' },
    { label: '状态', prop: 'status', isDictionary: true, dictionary: this.statusMap, showStatusIcon: true, isSort: true },
    { label: '操作', prop: 'oper', custom: true }
  ]

  get agentListArr () {
    const agents = deepClone(CommonModule.publicCache.userListObj)
    const agentsArr: any = []
    for (const i in agents) {
      agentsArr.push({ key: agents[i]._id, label: agents[i].name })
    }
    return agentsArr
  }

  private pageBack () {
    this.showPage = false
  }

  private batchClick (action, selectList) {
    this[action](selectList)
  }

  private addBtnFun () {
    this.showPage = true
    this.titleArr = ['满意度模版配置', '添加满意度模版']
    this.$nextTick(() => {
      this.addOrEditSatisfRef.setData()
    })
  }

  // 变更满意度模版状态
  private switchStatus (row: any, status: number) {
    const params = {
      id: row.id,
      status
    }
    this.$confirm(`确定要${status === 0 ? '停用' : '启用'}满意度模版吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      commonAction({ url: '/server-work/action/satisfaction/template/switch', method: 'post', data: params }).then(res => {
        if (res.success) {
          this.$message.success('变更满意度模版状态成功！')
          this.queryList()
        }
      })
    })
  }

  private sizeChange (size: number) {
    this.queueTablePages.pageSize = size
    this.queryList()
  }

  private currentChangeFun (page: number) {
    this.queueTablePages.current = page
    this.queryList()
  }

  private handleEdit (obj: any) {
    this.showPage = true
    this.titleArr = ['满意度模版配置', '添加满意度模版']
    this.$nextTick(() => {
      this.addOrEditSatisfRef.setData(obj)
    })
  }

  // 删除满意度模版
  private handleDel (row: any) {
    this.$confirm('确定要删除该满意度模版吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      commonAction({ url: '/server-work/action/satisfaction/template/delete/' + row.id, method: 'get' }).then(res => {
        if (res.success) {
          this.$message.success('删除！')
          this.queryList()
        }
      })
    })
  }

  private batchDelAgentFun (selectedArr: any) { // 批量删除
    this.$confirm('确定要批量删除技能组吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      let sendData = {}
      if (typeof selectedArr === 'object') { // 单个操作，传ids
        sendData = { ids: selectedArr || [] }
      } else { // 全选传查询条件
        sendData = { condition: { page: this.queueTablePages.current, limit: this.queueTablePages.pageSize, ...this.quickSearchForm.form } }
      }
      const actionData = { url: '/base/action/skillGroup/batch/delete', method: 'POST', data: sendData }
      organizationConfigModule.organizationCommonAction(actionData).then(res => {
        if (res) {
          this.$message.success('批量删除技能组成功')
          this.tableRef.cancelSelectFun() // 关闭批量操作栏
          this.queryList()
        }
      })
    })
  }

  private saveFun (type) {
    this.showPage = false
    this.queryList(type)
  }

  // 查询列表
  private queryList (addSuccess?: any) {
    if (addSuccess) { // 新增回到第一页
      this.queueTablePages.current = 1
    }
    const sendData = { page: { pageNumber: this.queueTablePages.current, pageSize: this.queueTablePages.pageSize }, ...this.quickSearchForm.form }
    const actionData = { url: '/server-work/action/satisfaction/template/list', method: 'POST', data: { ...sendData } }
    commonAction(actionData).then(res => {
      if (res.success) {
        const list = res.data.voList || []
        if (list.length === 0) {
          const page = Math.ceil(res.count / this.queueTablePages.pageSize)
          if (!res.count) { // 第一页且count为0是不再发请求（!res.count，以防后端没有返回count,直接死循环）
            this.queueTablePages.current = 1
          } else { // 删除到最后一个回到上一页
            this.queueTablePages.current = page
            this.queryList()
            return false
          }
        }
        list.forEach(item => {
          const agentObj = deepClone(CommonModule.publicCache.userListObj)[item.updateUser]
          item.updateUser = agentObj ? agentObj.name : '--'
        })
        this.queueTableData = list
        this.queueTablePages.total = res.data.page.total || 0
      }
    })
  }

  private back () {
    this.showPage = false
  }

  private mounted () {
    this.queryList()
  }

  private beforeMount () {
    this.batchOperate = this.batchOperate.filter(item => checkPermission(null, { value: [item._id] })) // 过滤批量操作的权限
  }
}
</script>

<style lang="stylus" scoped>
.queue-wrap
  width 100%
  height 100%
  position relative
.opera-span
  color $c-main
  margin-right 10px
  cursor pointer
.danger, .red-color
  color $c-danger
</style>
